package com.mindskip.xzs.utility;

import cn.hutool.core.collection.CollectionUtil;
import com.mindskip.xzs.base.BaseTreeNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
public class TreeUtil {

    //java8构建树

    /**
     * 将平铺的List<T>转换成Tree
     */
    public static <T extends BaseTreeNode> List<T> getTree(List<T> listNodes){
//        判断当前listNodes 是否为空
        if (CollectionUtil.isNotEmpty(listNodes)){
            //根据pid分组 key 都是parentId ,value 所有的permission对象
            Map<Integer, List<T>> listMap = listNodes.stream().collect(Collectors.groupingBy(t -> Optional.ofNullable(t.getParentId()).orElse(0)));
            //得到一级分类,第一级pid==0
            List<T> oneLevelClassify = listMap.get(0);
            //递归
            List<T> list = getChildList(oneLevelClassify, listMap);
            return list;
        }
        return new ArrayList<>();
    }

    /**
     * 获取子节点
     * @param classifies
     * @param groupMap
     * @param <T>  classifies：OL获取顶级部门     groupMap：根据parentId分组好的数据
     * @return
     */
    private static <T extends BaseTreeNode> List<T> getChildList(List<T> classifies, Map<Integer, List<T>> groupMap) {
        //判断一级的数据是否为空
       if (CollectionUtil.isNotEmpty(classifies)){
           //遍历 tree 父级对象
           for (T tree:classifies){
               //所有的二级的list对象
               List<T> classifyList = groupMap.get(tree.getId());
               //判断是否为空
               if (!CollectionUtils.isEmpty(classifyList)) {
                   tree.setChildren(classifyList);
                   getChildList(classifyList, groupMap);
               } else {
                   tree.setChildren(null);
               }
           }

           return classifies;
       }
       return new ArrayList<>();
    }

}
